#include <QLabel>
#include <QTimer>
#include <QFont>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QGraphicsDropShadowEffect>
#include <QDebug>
#include <QMessageBox>
#include <QRadioButton>
#include <QEvent>
#include <QPainter>
#include "widgetHarmonic.h"
#include <QDateTime>
#include <QMessageBox>
#include <cmath>
#include <QFontDatabase>
#include <math.h>

#define PAINTX 80

#define PAINTY 50

#define PI 3.1415927

#define LABELWIDTH 100
#define LABELHIGHTH 30

extern void voice();

widgetHarmonic::widgetHarmonic(QWidget *parent) :
    QWidget(parent)
{
    QFont ft;

    setStyleSheet(".QWidget{}");

    ft.setPixelSize(18);

    ft.setPixelSize(25);
//    btnStart = new myButton;
//    btnStart->setText("升源");
//    btnStart->setFont(ft);
//    btnStart->setFixedSize(90,80);

//pagedown_left

    ft.setPixelSize(20);
    tableView = new QTableView;
    tableView->setFixedSize(620,240);
    tableView->verticalHeader()->hide();
    tableView->setFont(ft);
    tableView->horizontalHeader()->setFont(ft);
    tableView->verticalScrollBar()->setStyleSheet("QScrollBar{background:transparent; width: 30px;}"
                                                  "QScrollBar::handle{background-color:rgb(30,66,100);min-height: 100px;}"
      "QScrollBar::handle:pressed{background:gray;}"
      "QScrollBar::sub-line{background:transparent;}"
      "QScrollBar::add-line{background:transparent;}");
    tableView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

    QStandardItemModel *model = new QStandardItemModel;
    model->setColumnCount(4);
    model->setHeaderData(0,Qt::Horizontal,tr(""));
    model->setHeaderData(1,Qt::Horizontal,tr("谐波含有率(%)"));
    model->setHeaderData(2,Qt::Horizontal,tr("谐波含量"));
    model->setHeaderData(3,Qt::Horizontal,tr("谐波相位"));

    QList<QStandardItem*> item;
    QString str = "";
    QStandardItem* item1= new QStandardItem(tr("基波"));
    QStandardItem* item2 = new QStandardItem(tr("0.000"));
    QStandardItem* item3 = new QStandardItem(tr("0.000"));
    QStandardItem* item4 = new QStandardItem(tr("0.00"));

    item << item1 << item2 << item3 << item4;
    model->appendRow(item);

    item.clear();

    for(int i=2;i<52;i++)
    {
        QStandardItem* itema= new QStandardItem;
        QStandardItem* itemb = new QStandardItem;
        QStandardItem* itemc = new QStandardItem;
        QStandardItem* itemd = new QStandardItem;
        str = QString::number(i) + "次";
        itema->setText(str);
        itemb->setText("0.000");
        itemc->setText("0.000");
        itemd->setText("0.00");
        item << itema << itemb << itemc << itemd;
        model->appendRow(item);
        item.clear();
    }

    model->item(0, 3)->setFlags(Qt::NoItemFlags);

    for(int i = 0;i < 4;i++)
    {
        for(int j = 0;j < 51;j++)
        {
            if(i == 0 || i == 2)
            {
               model->item(j, i)->setFlags(Qt::NoItemFlags); //第一列和第三列不可编辑
            }
            model->item(j, i)->setTextAlignment(Qt::AlignCenter);
        }
    }

    tableView->setModel(model);
    tableView->setColumnWidth(0,126);
    tableView->setColumnWidth(1,150);
    tableView->setColumnWidth(2,150);
    tableView->setColumnWidth(3,150);
    for(int i=0;i<model->rowCount();i++)
    {
        tableView->setRowHeight(i,40);
    }
    tableView->horizontalHeader()->setFixedHeight(40);
    tableView->setEditTriggers(QAbstractItemView::AllEditTriggers);
    //tableView->clearFocus();

//    QHBoxLayout *layoutResult1 = new QHBoxLayout;
//    layoutResult1->addStretch(1);
//    layoutResult1->addWidget(tableView);
//    layoutResult1->addStretch(1);

//    QVBoxLayout *layoutResult = new QVBoxLayout;
//    layoutResult->addStretch(1);
//    layoutResult->addSpacing(30);
//    layoutResult->addLayout(layoutResult1);
//    layoutResult->addStretch(1);

//    QGroupBox *boxTestResult = new QGroupBox;
//    boxTestResult->setLayout(layoutResult);

    //boxTestResult->setFixedSize(640,290);
    //boxTestResult->setTitle("- 谐波配置 -");
    //boxTestResult->setStyleSheet(".QGroupBox{border-radius:5px;font-size:20px;}QGroupBox:title{color:darkblue;}");

//pagedown_right
    ft.setPixelSize(20);

    Frequency = new QLineEdit("50");
    Frequency->setFixedSize(LABELWIDTH,40);
    Frequency->setFont(ft);
    Frequency->setAlignment(Qt::AlignCenter);
    Frequency->installEventFilter(this);
    Frequency->clearFocus();
    Frequency->setVisible(false);

//    QLabel *labFrequency_dw = new QLabel("Hz");
//    labFrequency_dw->setFixedSize(LABELWIDTH,40);
//    labFrequency_dw->setFont(ft);

//    QHBoxLayout *layoutFrequency = new QHBoxLayout;
//    layoutFrequency->addStretch(2);
//    layoutFrequency->addWidget(labFrequency);
//    layoutFrequency->addWidget(Frequency);
//    layoutFrequency->addWidget(labFrequency_dw);
//    layoutFrequency->addStretch(1);

    QLabel *labPassageway = new QLabel("通道选择：");
    labPassageway->setFixedSize(LABELWIDTH,40);
    labPassageway->setFont(ft);

    QListView* viewPassageway = new QListView();
    QSize size = viewPassageway->sizeHint();
    size.setHeight(30);
    viewPassageway->setGridSize(size);

    Passageway = new QComboBox();
    Passageway->setFixedSize(LABELWIDTH,50);
    Passageway->setFont(ft);
    Passageway->setView(viewPassageway);

    QStringList  PassagewayA = QStringList() <<" UA "<<" UB "<<" UC "<<" IA "<<" IB "<<" IC ";
    Passageway->addItems( PassagewayA);
    Passageway->setCurrentIndex(0);

    QHBoxLayout *layoutPassageway = new QHBoxLayout;
    layoutPassageway->addStretch(2);
    layoutPassageway->addWidget(labPassageway);
    layoutPassageway->addWidget(Passageway);
    layoutPassageway->addSpacing(105);
    layoutPassageway->addStretch(1);

    DataClear = new myButton();
    DataClear->setText("数据清零");
    DataClear->setFont(ft);
    DataClear->setFixedSize(3*LABELWIDTH,50);

    QHBoxLayout *layoutBtnline1 = new QHBoxLayout;
    layoutBtnline1->addStretch(2);
    //layoutBtnline1->addWidget(WaveScan);
    //layoutBtnline1->addSpacing(10);
    layoutBtnline1->addWidget(DataClear);
    layoutBtnline1->addSpacing(105);
    layoutBtnline1->addStretch(1);

    Save_setting = new myButton();
    Save_setting->setText("配    置");
    Save_setting->setFont(ft);
    Save_setting->setFixedSize(3*LABELWIDTH,50);

    QHBoxLayout *layoutBtnline2 = new QHBoxLayout;
    layoutBtnline2->addStretch(2);
    layoutBtnline2->addWidget(Save_setting);
    layoutBtnline2->addSpacing(105);
    layoutBtnline2->addStretch(1);

    QVBoxLayout *layoutTestCfg = new QVBoxLayout;
    layoutTestCfg->addStretch(1);
//    layoutTestCfg->addLayout(layoutFrequency);
    layoutTestCfg->addLayout(layoutPassageway);
    layoutTestCfg->addStretch(1);
    layoutTestCfg->addLayout(layoutBtnline1);
    layoutTestCfg->addStretch(1);
    layoutTestCfg->addLayout(layoutBtnline2);
    layoutTestCfg->addStretch(1);

    QGroupBox *boxTestCfg = new QGroupBox;
    boxTestCfg->setLayout(layoutTestCfg);
    boxTestCfg->setFixedSize(350,290);
    //boxTestCfg->setTitle("- 基波控制 -");
    boxTestCfg->setStyleSheet(".QGroupBox{border-radius:5px;font-size:20px;}QGroupBox:title{color:darkblue;}");

    QHBoxLayout *layoutDown = new QHBoxLayout;
    layoutDown->setContentsMargins(20,10,10,10);
    layoutDown->addWidget(tableView);
    layoutDown->addWidget(boxTestCfg);

    QLabel *labBlank = new QLabel("");
    labBlank->setFixedSize(1000,2);
    labBlank->setStyleSheet("background-color:lightgray;");

    QVBoxLayout *layoutMain = new QVBoxLayout;
    layoutMain->setContentsMargins(10,0,0,10);
    layoutMain->addLayout(layoutDown);
    layoutMain->addWidget(labBlank);

    setLayout(layoutMain);

    //widget info
    widgetInfo = new QWidget(this);
    widgetInfo->setStyleSheet(".QWidget{background-color:qColor(250,250,0,150);border-radius:15px;}");
    labInfo = new QLabel("欢迎使用...");
    labInfo->setStyleSheet("color:yellow;font:22px;font-weight:bold;");
    labInfo->setFixedWidth(280);
    labInfo->setAlignment(Qt::AlignCenter);

    QVBoxLayout *layoutInfo = new QVBoxLayout;
    layoutInfo->setAlignment(Qt::AlignCenter);
    layoutInfo->addWidget(labInfo);

    widgetInfo->setLayout(layoutInfo);
    widgetInfo->setFixedSize(450,60);
    widgetInfo->move(370,260);
    widgetInfo->setVisible(false);

    //QTimer::singleShot(1000, this, SLOT(widgetInfoHide()));
//    connect(btnStart, SIGNAL(clicked(QString)),this,SLOT(startTest()));
    connect(Save_setting, SIGNAL(clicked()),this,SLOT(set_saved()));

    QAbstractItemModel *modessl = tableView->model();
    connect(modessl,SIGNAL(dataChanged(QModelIndex,QModelIndex)),this,SLOT(tableViewItem_change(QModelIndex,QModelIndex)));
    connect(DataClear,SIGNAL(clicked(bool)),this,SLOT(waveClear()));
    init();

    isInTesting = false;

    waveView = false;

    send_tmp = "";

}

void widgetHarmonic::init() //显示上次设置的谐波源参数
{
    QString tmp_value = "";
    QString str = "";
    QStringList m;
    int i = 0,j = 0;

    QAbstractItemModel *modessl = tableView->model();
    QModelIndex indextemp;

    QSettings *Last_data = new QSettings("current_data.ini", QSettings::IniFormat);
    int Passageway_style = Last_data->value("Current/Passageway").toInt();
    QString frequency = Last_data->value("Current/Frequency").toString();

    Passageway->setCurrentIndex(Passageway_style);
    Frequency->setText(frequency);

    for(i=0; i < 51; i++)
    {
        str = "Current/" + QString::number(i);
        tmp_value = Last_data->value(str,"error").toString();
        j = 0;
        if(tmp_value != "error")
        {
            m = tmp_value.split(',');
            for(j = 0;j < m.count();j++)
            {
                indextemp = modessl->index(i,j+1);
                modessl->setData(indextemp,m.at(j));
            }
        }
        str.clear();
    }

    delete Last_data;
}

QString widgetHarmonic::change_data(int style, QString data)
{
    int i=0,j=0;
    QString data_changed = "";
    QString reData = "";
    for(i = 0;i < data.length();i++)
    {
        if(data[i] != '.')
        {
            data_changed.append(data[i]);
        }
    }

    if(style == 0)
    {
        if(data_changed.length() < 6)
        {
            j = data_changed.length();
            j = 6 - j;
            for(i=0;i<j;i++)
            {
                reData.append("0");
            }
            if(i == j)
            {
                reData.append(data_changed);
                return reData;
            }
        }
    }
    else if(style == 1)
    {
        if(data_changed.length() < 5)
        {
            j = data_changed.length();
            j = 5 - j;
            for(i=0;i<j;i++)
            {
                reData.append("0");
            }
            if(i == j)
            {
                reData.append(data_changed);
                return reData;
            }
        }
    }
    else if(style == 2)
    {
        if(data_changed.length() < 2)
        {
            j = data_changed.length();
            j = 2 - j;
            for(i=0;i<j;i++)
            {
                reData.append("0");
            }
            if(i == j)
            {
                reData.append(data_changed);
                return reData;
            }
        }
    }
    return 0;
}

//void pageVolt2Ampere::voice()//蜂鸣器多声
//{
////#ifndef i386
////    int fd ;
////    int i=0;
////    fd = open("/dev/pwm", 'r');
////    if(count == 0)
////    {
////        while( i<3)
////        {
////            ::ioctl(fd, 1, 1000);
////            ::usleep(80000);
////            ::ioctl(fd,0);
////            i++;
////            ::usleep(80000);
////        }
////    }
////    else if(count == 1)
////    {
////        ::ioctl(fd,1,1000);
////        ::usleep(80000);
////        ::ioctl(fd,0);
////    }
////    ::close(fd);
////#else
////    if(count == 10)
////        qDebug()<<"beer";
////#endif
//#ifndef i386
//    int fd ;
//    fd = ::open("/dev/pwm", 'r');
//    ::ioctl(fd,1,1000);
//    ::sleep(8);
//    ::ioctl(fd,0);
//    ::close(fd);
//#endif
//    qDebug()<<"beeper";
//}

void widgetHarmonic::tableViewItem_change(QModelIndex index,QModelIndex index1)
{
    int i = 0;
    float tmp = 0 ;
    QAbstractItemModel *modessl = tableView->model();
    for(i = 0;i < 51;i++)
    {
        tmp = (modessl->data(modessl->index(i,1)).toFloat()) / 100.0 * 6.3;
        index = modessl->index(i,2);
        modessl->setData(index,QString::number(tmp));
        tmp = 0.0;
    }
}

void widgetHarmonic::showTcpData(QString style, QString Netstr)
{
    QString m = "";
    QStringList strlist;

    int row = 0;

    QAbstractItemModel *modessl = tableView->model();
    QModelIndex indextemp;

    strlist = Netstr.split('$');
    qDebug()<<strlist.count();

    for(int i=0;i<strlist.count();i++)
    {
       m.append(strlist.at(i));
       qDebug()<<"value of m"<<m;

       if(style == "基波") row = 0;
       else if(style == "2次") row = 1;
       else if(style == "3次") row = 2;
       else if(style == "4次") row = 3;
       else if(style == "5次") row = 4;
       else if(style == "6次") row = 5;
       else if(style == "7次") row = 6;
       else if(style == "8次") row = 7;
       else if(style == "9次") row = 8;
       else if(style == "10次") row = 9;
       else if(style == "11次") row = 10;
       else if(style == "12次") row = 11;
       else if(style == "13次") row = 12;

       if(i == 0)
       {
           indextemp = modessl->index(row,1);
       }
       if(i == 1)
       {
           indextemp = modessl->index(row,3);
       }
       modessl->setData(indextemp,m);
       m.clear();
    }
}

void widgetHarmonic::resolveTCPData(QString Netstr)
{
    QString style = "";

    QString m = "";
    QStringList strlist;

    Netstr = Netstr.simplified();
    if(Netstr.left(4) == "work" || Netstr.left(4) == "stop")
    {
        if(Netstr.left(4) == "work")
        {
            Netstr = Netstr.mid(4);
            strlist = Netstr.split('#');
            qDebug()<<strlist.count();
            for(int i=0;i<strlist.count();i++)
            {
               m.append(strlist.at(i));
               qDebug()<<"value of m"<<m;
               if(i < 13)
               {
                   if(i == 0) style = "基波";
                   else if(i == 1) style = "2次";
                   else if(i == 2) style = "3次";
                   else if(i == 3) style = "4次";
                   else if(i == 4) style = "5次";
                   else if(i == 5) style = "6次";
                   else if(i == 6) style = "7次";
                   else if(i == 7) style = "8次";
                   else if(i == 8) style = "9次";
                   else if(i == 9) style = "10次";
                   else if(i == 10) style = "11次";
                   else if(i == 11) style = "12次";
                   else if(i == 12) style = "13次";
                   showTcpData(style,m);
               }
               else
               {
                   if(i == 13)
                   {
                       Passageway->setCurrentIndex(m.toInt());
                   }
               }
               m.clear();
            }
        }
        set_saved();
    }
    else if(Netstr.left(4) == "wave")
    {
        makewave();
    }
    else if(Netstr.left(4) == "dump")
    {
        waveClear();
    }
    Netstr = Netstr.mid(Netstr.length());

    sendTcpBuf.append("1");
    sendTcpBuf.append("\r\n");
    emit TcpSend();
    sendTcpBuf.clear();
}

void widgetHarmonic::set_saved()
{
    tableView->setFocusPolicy(Qt::NoFocus);

    int i = 0;
    float sum = 0.0;
    int table_item1 = 0;
    unsigned char cmd ;
    unsigned char temp ;
    QString result = "";
    sendBuf.resize(0);
    qDebug()<<"start sendBuf"<<sendBuf.toHex();

    QAbstractItemModel *modessl = tableView->model();
    cmd = Passageway->currentIndex() + 0x31;

    sendBuf.resize(0);
    sendBuf.append(0xAB);
    sendBuf.append(0x98);
    sendBuf.append(cmd);

    for(i=0; i<51; i++)
    {
        table_item1 = modessl->data(modessl->index(i,1)).toInt();
        sendBuf.append(table_item1 & 0xFF);

        result.append(modessl->data(modessl->index(i,1)).toString());
        result.append(",");

        result.append(modessl->data(modessl->index(i,2)).toString());
        result.append(",");

        result.append(modessl->data(modessl->index(i,3)).toString());
        result.append("$");

        sum = sum + (modessl->data(modessl->index(i,1)).toFloat());
    }

    for(i = 1;i<51;i++)
    {
        table_item1 = modessl->data(modessl->index(i,3)).toDouble() * 100;
        temp = (table_item1 >> 8) & 0xFF;
        sendBuf.append(temp);
        temp = table_item1 & 0xFF;
        sendBuf.append(temp);
    }

    if(sum > 100.0)
    {
        QMessageBox::warning(this,tr("错误"),tr("谐波含有率总和超过100%,请重新设置！"),QMessageBox::Ok);

        isInTesting = false;

        tableView->setEnabled(true);

        result.clear();
    }
    else
    {
        qDebug()<<"set_saved(), sendBuf is"<<sendBuf.toHex() << sendBuf.size();
        emit cmdSend();
        save_data(result,0);
    }
}

void widgetHarmonic::recvResult(QByteArray rcvdByte)
{
     if(!isInTesting) return;

     int length = 0;

     length = rcvdByte[1];

     qDebug()<<"pageVolt2Ampere, result:"<<rcvdByte.toHex();

     tableView->setEnabled(true);

     if((unsigned char)rcvdByte[0] == 0xff)
     {
         widgetInfo->hide();

         labInfo->setText("错误,无法链接到硬件!");
         widgetInfo->show();

         QTimer::singleShot(2000, this, SLOT(widgetInfoHide()));

         isInTesting = false;

         sendBuf.clear();

         return;
     }

     if(length == 1)
     {
         if((unsigned char)rcvdByte[2] == 0x00)
         {
            emit cmdSend();
            qDebug()<<"pagevolt2ampere"<<sendBuf.toHex();
         }
         else if((unsigned char)rcvdByte[2] == 0x01)
         {
             labInfo->setText("谐波输出设置成功！");
             widgetInfo->show();

             QTimer::singleShot(3000, this, SLOT(widgetInfoHide()));

             sendBuf.clear();

             sendTcpBuf.append("1");
             sendTcpBuf.append("\r\n");
             emit TcpSend();

             isInTesting = false;
         }
     }
     rcvdByte.clear();
}

void widgetHarmonic::save_data(QString result,int style)
{
    QStringList tmp_str;
    QString str = "";
    int i = 0,j = 0;

    tmp_str = result.split('$');

    if(style == 0)
    {
        QSettings *current_data = new QSettings("current_data.ini", QSettings::IniFormat);
        current_data->beginGroup("Current");
        current_data->setValue("Passageway",QString::number(Passageway->currentIndex()));
        current_data->setValue("Frequency",Frequency->text());
        for(j = 0; j < tmp_str.count() -1;j++)
        {
            str = tmp_str.at(j);
            current_data->setValue(QString::number(j),str);
        }
        delete current_data;
    }
    else if(style == 1)
    {
        qDebug()<<"tmp_str.count()"<<tmp_str.count();
        for(i = 0;i < 6;i ++)
        {
            QSettings *all_data = new QSettings("all_data.ini", QSettings::IniFormat);
            if(i == 0)
            {
                all_data->beginGroup("UA");
            }
            else if(i == 1)
            {
                all_data->beginGroup("IA");
            }
            else if(i == 2)
            {
                all_data->beginGroup("UB");
            }
            else if(i == 3)
            {
                all_data->beginGroup("IB");
            }
            else if(i == 4)
            {
                all_data->beginGroup("UC");
            }
            else if(i == 5)
            {
                all_data->beginGroup("IC");
            }
            j = 0;
            for(j = 0; j < tmp_str.count() -1;j ++)
            {
                str = tmp_str.at(j);
                if(j == 0)
                {
                    str.append(",");
                    str.append(Frequency->text());
                }
                all_data->setValue(QString::number(j),str);
            }
            delete all_data;
        }
    }
}

QString widgetHarmonic::findFloatStr(QByteArray str)
{
    QByteArray showStr(str);

    if((unsigned char)showStr[0] == 0x20)
    {
        showStr = showStr.mid(1);
    }
    else
    {
        showStr[0] = '-';
    }

    for(int i = 0; i < showStr.length(); i++)
    {
        if((unsigned char)showStr[i] == 0x2e)
        {
            showStr[i] = '.';
        }
    }

    return showStr;
}

void widgetHarmonic::setDataStyle(QLineEdit *lab)
{
    QFont ft;
    ft.setPixelSize(17);

    lab->setFixedSize(130,25);
    lab->setFont(ft);
    lab->setAlignment(Qt::AlignCenter);
}

void widgetHarmonic::makewave()
{
    //voice();
    tableView->setEnabled(false);
    if(!waveView)
    {
        tableView->setEnabled(true);
        waveView = true;
        //plotTimer->start(1000);
    }
    else
    {
        return;
    }
}

void widgetHarmonic::waveClear()
{
    waveView = false;



    sendBuf.resize(0);
    sendBuf.append(0xAB);
    sendBuf.append(0x01);
    sendBuf.append(0x37);

    qDebug()<<"clear(), sendBuf is"<<sendBuf.toHex();
    emit cmdSend();

    int i = 0,j = 0;
    QString reslut = "";

    QAbstractItemModel *modessl = tableView->model();
    QModelIndex indextemp;

    for(i=0; i < 51; i++)
    {
        for(j = 1;j < 4; j++)
        {
            indextemp = modessl->index(i,j);
            modessl->setData(indextemp,"0.000");
        }
        reslut.append("0.000");
        reslut.append(",");
        reslut.append("0");
        reslut.append(",");
        reslut.append("0.000");
        reslut.append("$");
    }
    save_data(reslut,0);
}

void widgetHarmonic::DataInit()
{
    init();

    waveView = false;

    isInTesting = false;

//    dataGraph0->clear();

//    myPlot->replot();

//    plotTimer->stop();

    sendBuf.clear();

    sendTcpBuf.clear();

    labInfo->setText("欢迎使用...");
    widgetInfo->show();
    QTimer::singleShot(1000, this, SLOT(widgetInfoHide()));
}
